<?php

class Application_Model_Mapper_GroupMapper
{
	protected $_dbTable;

	public function setDbTable ($dbTable)
	{
		
		if (is_string($dbTable))
		{
			$dbTable = new $dbTable();
		}
		if (! $dbTable instanceof Zend_Db_Table_Abstract)
		{
			throw new Exception('Invalid table data gateway provided');
		}
		$this->_dbTable = $dbTable;
		return $this;
		
	}

	public function getDbTable ()
	{
		
		if (null === $this->_dbTable)
		{
			$this->setDbTable('Application_Model_DbTable_Group');
		}
		return $this->_dbTable;
		
	}

	public function add (Application_Model_Group $group)
	{		
		
		
		$generatedid = Helper_Idgenerator::getid();
		$generatedidcheck = $this->fetchID($generatedid);
		if(empty($generatedidcheck)){
		
			$data = array(
					'id' => $generatedid,
					'name' => $group->getname(),
					'ersteller' => $group->getErsteller(),
			);
	
			return $this->getDbTable()->insert($data);
		}
		else{
			$this->add($group);
		}
		
	}
	
	
	public function update ($daten, $groupid)
	{
		$table = $this->getDbTable();
		$where = $table->getAdapter()->quoteInto('id = ?', $groupid);
		$table->update($daten, $where);
	}

	public function delete ($id)
	{
		$mappergroupmember = new Application_Model_Mapper_GroupmemberMapper;
		$mappergroupmember->deletegroup($id);

		$table = $this->getDbTable();
		$where = $table->getAdapter()->quoteInto('id = ?', $id);
		$table->delete($where);
	}


	public function fetchID($id)
	{
		$db = Zend_Db_Table::getDefaultAdapter();
		$entry = new Zend_Db_Select($db);
		$entry->from('group');
		$entry->where('group.id = ?', $id);
		return $entry->query()->fetch();
	}

	public function fetchErsteller($id)
	{
 		$db = Zend_Db_Table::getDefaultAdapter();
 		$entry = new Zend_Db_Select($db);
// 		$entry = $this->getDbTable();
		$entry->from('group');
		$entry->where('group.ersteller = ?', $id);
		return $entry->query()->fetchall();
	}
	
	public function fetchGroupandMember($id)
	{
		$db = Zend_Db_Table::getDefaultAdapter();
		$entry = new Zend_Db_Select($db);
		// 		$entry = $this->getDbTable();
		$entry->from('group');
		$entry->where('group.ersteller = ?', $id);
		$list =  $entry->query()->fetchall();
		

		$mappergroup = new Application_Model_Mapper_GroupmemberMapper();
		$listback = array();

		$i = 0;
		foreach ($list as $array){		
			$listback[$i] = array(
					'id' => $array['id'],
					'name' => $array['name'],
					'groupmember' => $mappergroup->fetchGroupid($array['id']));
			++$i;
		}
		
		return $listback;
	}
}




